package com.hi.cdi.versioning.repository;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.hi.cdi.versioning.domain.Book;
import com.hi.cdi.versioning.domain.Book_History;
import com.mongodb.WriteResult;

@Component
public class BookDao {

	@Autowired
	private MongoTemplate mongoTemplate;

	public void save(Book book) {
		mongoTemplate.insert(Book_History.prepareNewHistoryRecord(book));
		mongoTemplate.insert(book);
	}

	public void update(Book book) {
		Query query = Query.query(Criteria.where("title").is(book.getTitle()));
		Update update = new Update();
		if (StringUtils.isNotBlank(book.getAuthor())) {
			update.set("author", book.getAuthor());
		}
		if (book.getPrice() != 0.0d) {
			update.set("price", book.getPrice());
		}
		Class<?> entityClass = Book.class;
		WriteResult writeResult = mongoTemplate.updateFirst(query, update, entityClass);
		writeResult.getLastError();
		Book persitedBook = mongoTemplate.findOne(query, Book.class);
		mongoTemplate.insert(Book_History.prepareNewHistoryRecord(persitedBook));
	}
}
